package cn.com.dcsgo.service.impl;

import cn.com.dcsgo.feign.ProductFeignClient;
import cn.com.dcsgo.mapper.OrderMapper;
import cn.com.dcsgo.mapper.OrderProductMapper;
import cn.com.dcsgo.order.bean.Order;
import cn.com.dcsgo.product.bean.Product;
import cn.com.dcsgo.service.OrderService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.List;

/**
 * OrderServiceImpl
 *
 * @author Dcsgo
 * @since 2025/3/11 9:48
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class OrderServiceImpl implements OrderService {
    private final DiscoveryClient discoveryClient;
    private final RestTemplate restTemplate;
    /**
     * 负载均衡器
     * 需要导入 spring-cloud-starter-loadbalancer 组件
     */
    private final LoadBalancerClient loadBalancerClient;

    private final OrderMapper orderMapper;
    private final OrderProductMapper orderProductMapper;
    private final ProductFeignClient productFeignClient;

    /**
     * 使用注解指定 Sentinel 资源
     * Sentinel 资源默认包括 web 资源 RPC 资源等
     * SentinelResource 注解通常用来指定
     * 非 web(controller)层 的资源
     * blockHandler 用来指定触发流控规则时的处理方法名
     *
     * @param userId    userId
     * @param productId productId
     * @return Order
     */
    @Override
    @SentinelResource(value = "createOrder", blockHandler = "createOrderBlockHandler")
    public Order createOrder(Long userId, Long productId) {
        Order order = new Order();
        order.setId(1L);
        //RPC 获取总金额
        //Product product = getProductFromRemoteWithLoadBalancerAnnotation(productId);
        Product product = productFeignClient.getProductById(productId);
        BigDecimal totalAmount = product.getPrice().multiply(new BigDecimal(product.getNum()));
        order.setTotalAmount(totalAmount);
        order.setUserId(userId);
        order.setNickName("Dcsgo");
        order.setAddress("华夏");
        //RPC 获取商品列表
        order.setProductList(List.of(product));
        orderMapper.insert(order);
        log.debug("order: {}", order);
        return order;
    }

    /**
     * createOrder 的 blockHandler
     * 要求返回类型、参数列表与 createOrder 兼容
     * 最后的 BlockException 参数会自动注入
     *
     * @param userId    userId
     * @param productId productId
     * @param e         productId
     * @return Order
     */
    public Order createOrderBlockHandler(Long userId, Long productId, BlockException e) {
        return new Order(0L,
                new BigDecimal(0),
                userId, "未知用户名",
                e.getClass() + " : " + e.getMessage(),
                null);
    }

    /**
     * 基于注解的负载均衡的远程调用
     *
     * @param productId productId
     * @return Product
     */
    private Product getProductFromRemoteWithLoadBalancerAnnotation(Long productId) {
        //http://微服务名/product/1
        String url = "http://service-product" + "/product/" + productId;
        log.info("RPC: {}", url);
        return restTemplate.getForObject(url, Product.class);
    }

    /**
     * 负载均衡的远程调用
     *
     * @param productId productId
     * @return Product
     */
    private Product getProductFromRemoteWithLoadBalancer(Long productId) {
        //获取微服务实例的url进行RPC
        ServiceInstance chooseInstance = loadBalancerClient.choose("service-product");
        //http://localhost:8001/product/1
        String url = "http://" + chooseInstance.getHost() + ":" + chooseInstance.getPort() + "/product/" + productId;
        log.info("RPC: {}", url);
        return restTemplate.getForObject(url, Product.class);
    }

    /**
     * 无负载均衡的远程调用
     *
     * @param productId productId
     * @return Product
     */
    private Product getProductFromRemote(Long productId) {
        //获取微服务实例的url进行RPC
        ServiceInstance instance = discoveryClient.getInstances("service-product").get(0);
        //http://localhost:8001/product/1
        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;
        log.info("RPC: {}", url);
        return restTemplate.getForObject(url, Product.class);
    }
}
